﻿using System;
using System.Collections.Generic;
using System.Linq;
using PetaPoco;
using System.Diagnostics;
using AppManager.Model;

namespace PushTask
{
    /// <summary>
    /// pushsharp的推送
    /// </summary>
    public class Push
    {
        public static void Send()
        {
            Database db = new Database();
            string path = AppDomain.CurrentDomain.BaseDirectory;
            string certificatePath = path.Substring(0, path.TrimEnd('\\').LastIndexOf('\\')) + @"\Certificate\";


            LogHelper.WriteCreateNewLog("info", "开始执行");

            List<Message> needSendList = GetNeedSendMessageList(db);

            if (needSendList.Count() == 0)
            {
                LogHelper.WriteCreateNewLog(LogType.info, "没有需要发送的消息list.Count==0");
                return;
            }
            else
            {
                LogHelper.WriteCreateNewLog(LogType.info, "本次需要发送的消息list.Count=" + needSendList.Count());
            }

            //按项目分组发送
            var mg = needSendList.GroupBy(s => s.ProjectId).Select(s => new { s.Key, List = s.ToList() });
            foreach (var g in mg)
            {
                var list = g.List;

                try
                {
                    PushSharpSend.ApnsSend(certificatePath, list);
                    PushSharpSend.GcmSend(list);
                }
                catch (Exception ex)
                {
                    LogHelper.WriteCreateNewLog(LogType.error, "Push.Send发成错误：" + ex.Message);
                }
            }

            LogHelper.WriteCreateNewLog(LogType.info, "结束执行");
        }

        /// <summary>
        /// 獲取需要發送的消息
        /// </summary>
        /// <param name="db"></param>
        /// <returns></returns>
        public static List<Message> GetNeedSendMessageList(Database db)
        {
            Stopwatch sw = Stopwatch.StartNew();
            var messageList = db.Fetch<Message>("select * from smview");

            List<int> hasfinishList = new List<int>();//保存所有已經發送完畢的
            //hasfinishList.Add(-1);
            //foreach (var m in messageList)
            //{
            //    var count = db.ExecuteScalar<int>("select count(0) from messagedevice where messageId=@0 and remoteserverresult=0 and sendresult<>1", m.Id);
            //    if (count == 0)
            //    {
            //        hasfinishList.Add(m.Id);
            //    }
            //}

            //db.Execute("update message set IsFinshed = 1 where id in (@0)", hasfinishList);
            sw.Stop();
            Console.WriteLine(sw.Elapsed);
            return messageList;
        }
    }
}
